Hi people, Im making a text editor and I have a big problem, here is the code where I have the problem
Code:
mytext = new char[count+lenght];
I have debugged my program many times and Im sure that count == 0 and lenght == 6, yet mytext always ends up bigger and when I print it on the screen it ends up printing a lot of giberish thats shouldnt be there!
Here is the .cpp file
Code:
#include "main.h"
int main() {
Text paper;
char test[] = "Marcos";
paper.addtext(test, strlen(test));
paper.showtext();
return 0;
}
// Class Text
Text::Text() {
mytext = new char[1];
mytext = NULL;
count = 0;
}
Text::~Text() {
delete[] mytext;
}
void Text::addtext(char *a, int lenght) {
char *temp; // temporarily hold what was already on mytext
if (mytext != NULL) {
temp = new char[count];
strcpy(temp, mytext);
delete[] temp;
} else {
temp = "";
}
delete[] mytext;
mytext = new char[count+lenght]; // make it long enough to hold what it had before + what we will add new
for (int i = 0; i < count; i++)
mytext[i] = temp[i]; // add what we had before
for (int i = 0; i < lenght; i++)
mytext[count+i] = a[i]; // add the new text after what we had before
}
void Text::deletetext() {
}
void Text::showtext() {
printf("%s", mytext);
}
Here is the .h file
Code:
#include <stdlib.h>
#include <fstream>
class Text {
public:
Text();
~Text();
void addtext(char *, int);
void deletetext();
void showtext();
private:
char *mytext;
int count;
};
Sorry for the trouble guys, but I really cant solve this.